package com.example.chengzhengwei;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

import java.text.DecimalFormat;

public class EnterTestActivity extends AppCompatActivity {

    private EditText editTextTemperature, editTextTimeMinutes, editTextTimeSeconds, editTextFluorescencePeriod;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_test);

        dbHelper = new DatabaseHelper(this);

        editTextTemperature = findViewById(R.id.editTextTemperature);
        editTextTimeMinutes = findViewById(R.id.editTextTimeMinutes);
        editTextTimeSeconds = findViewById(R.id.editTextTimeSeconds);
        editTextFluorescencePeriod = findViewById(R.id.editTextFluorescencePeriod);

        Button buttonConfirm = findViewById(R.id.buttonConfirm);
        Button buttonCancel = findViewById(R.id.buttonCancel);

        buttonConfirm.setOnClickListener(v -> {
            Intent intent = new Intent(EnterTestActivity.this, RunActivity.class);
            startActivity(intent);
            finish();
        });

        buttonCancel.setOnClickListener(v -> {
//            Intent intent = new Intent(EnterTestActivity.this, MainActivity.class);
//            startActivity(intent);
            finish();
        });

        loadSavedData();
    }

    private void loadSavedData() {
        Cursor cursor = dbHelper.getAllData();
        if (cursor != null && cursor.moveToFirst()) {
            int temperatureIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TEMPERATURE);
            int timeMinutesIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TIME_MINUTES);
            int timeSecondsIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TIME_SECONDS);
            int fluorescencePeriodIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_FLUORESCENCE_PERIOD);

            if (temperatureIndex != -1) {
                double temperature = cursor.getDouble(temperatureIndex);
                editTextTemperature.setText(new DecimalFormat("#.#").format(temperature));
            }
            if (timeMinutesIndex != -1) {
                int timeMinutes = cursor.getInt(timeMinutesIndex);
                editTextTimeMinutes.setText(String.valueOf(timeMinutes));
            }
            if (timeSecondsIndex != -1) {
                int timeSeconds = cursor.getInt(timeSecondsIndex);
                editTextTimeSeconds.setText(String.valueOf(timeSeconds));
            }
            if (fluorescencePeriodIndex != -1) {
                int fluorescencePeriod = cursor.getInt(fluorescencePeriodIndex);
                editTextFluorescencePeriod.setText(String.valueOf(fluorescencePeriod));
            }

            cursor.close();
        }
    }
}